package com.example.mediademo.opengl;

import android.opengl.GLES20;
import android.opengl.GLES30;
import android.opengl.GLSurfaceView;
import android.util.Log;

import com.example.mediademo.Configs;

import java.util.ArrayList;
import java.util.List;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class SimpleRender implements GLSurfaceView.Renderer {

    private IDrawder mDrawder;
    private List<IDrawder> mDrawerList = new ArrayList<>();

    public SimpleRender(IDrawder drawder) {
        mDrawerList.add(drawder);
    }

    public void addDrawer(IDrawder drawder) {
        mDrawerList.add(drawder);
    }

    @Override
    public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) {
        Log.d(Configs.TAG, "onSurfaceCreated");
        // 清屏
        GLES20.glClearColor(0f, 0f, 0f, 0f);
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
        // 开启混合模式(设置透明度可生效)
//        GLES20.glEnable(GLES20.GL_BLEND);
        // 配置混合算法
//        GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA,GLES20.GL_ONE_MINUS_SRC_ALPHA);
        // 生成纹理id
        int[] textureIds = OpenGLTools.createTextureIds(mDrawerList.size());
        // 设置纹理id
//        mDrawder.setTextureID(OpenGLTools.createTextureIds(1)[0]);
        for (int i = 0; i < mDrawerList.size(); i++) {
            mDrawerList.get(i).setTextureID(textureIds[i]);
        }
    }

    @Override
    public void onSurfaceChanged(GL10 gl10, int w, int h) {
        Log.d(Configs.TAG, "onSurfaceChange  w:" + w + " h:" + h);
        // 设置绘制区域的宽高和位置
        GLES20.glViewport(0, 0, w, h);
        for (IDrawder drawer : mDrawerList) {
            drawer.setWindowSize(w,h);
        }
    }

    /**
     * 该接口会不断回调,刷新绘制区域
     *
     * @param gl10
     */
    @Override
    public void onDrawFrame(GL10 gl10) {
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
        Log.d(Configs.TAG,"onDraw");
//        mDrawder.draw();
        for (IDrawder drawder : mDrawerList) {
            drawder.draw();
        }
    }
}
